package com.supermali.behavior;

import com.supermali.entity.MapImageAbstract;
import com.supermali.entity.npc.IntesectDirect;
import com.supermali.entity.npc.finish.FinishAbstract;
import com.supermali.entity.npc.monistor.MonistorAbstract;
import com.supermali.entity.npc.person.Person;

import java.util.HashSet;
import java.util.Set;

public class Gravity {

    // 间隔时间
    public static final double t= 0.06;
    // 加速度
    public static final double g =9.8;
    // 下降的初始速度
    private double v0 ;

    private MapImageAbstract mapImageAbstract;

    // 下降是否结束
    private boolean isOver;
    // 下降总时间
    private double totalTime = 0;

    public Gravity(MapImageAbstract mapImageAbstract) {
        this.mapImageAbstract = mapImageAbstract;
        this.isOver = true;
        v0=0;
    }

    // 重力掉落
    private void down(){
        isOver = false;
        totalTime+=t;
        double h = mapImageAbstract.getY() - 0.5 * g * t * totalTime;
        mapImageAbstract.setY(h);
    }
    /**
     * 结束下落
     * */
    public void overDown(){
        isOver=true;
        totalTime=0;
        v0=0;
    }

    private Set<IntesectDirect> getSets(){
        // 校验该对象是否已经在某个支撑物的上面
        Set<IntesectDirect> intesectDirects = new HashSet<>();
        if(mapImageAbstract instanceof MonistorAbstract){
            intesectDirects = ((MonistorAbstract) mapImageAbstract).checkCollide();
        }else if(mapImageAbstract instanceof Person){
            intesectDirects = ((Person) mapImageAbstract).checkCollide();
        }else if(mapImageAbstract instanceof FinishAbstract){
            intesectDirects = ((FinishAbstract) mapImageAbstract).checkCollide();
        }
        return intesectDirects;
    }

    public void autoDown(){
        Set<IntesectDirect> intesectDirects = getSets();
        // 判断是否是有支撑物
        boolean haveTop = false;
        for(IntesectDirect direct: intesectDirects){
            if(direct.getDirect()==IntesectDirect.Direct.TOP){
                haveTop = true;
                isOver=true;
                totalTime=0;
                v0=0;
            }
        }
        if(!haveTop){
            this.down();
        }
    }

    public boolean isOver() {
        return isOver;
    }

    public void setV0(double v0) {
        this.v0 = v0;
    }
}
